using System.Collections.Generic;
using System;
using System.Linq;

namespace Polymod.TemplateBuilders
{

    public class AffectedModelTemplateBuilder : ModelTreeTemplateBuilder, IAffected
    {
        private readonly Dictionary<Type, Dictionary<string, HashSet<string>>> _affectedProperties = new Dictionary<Type, Dictionary<string, HashSet<string>>>();

        protected override Type GetModelBaseType(ModelTemplateParameters parameters)
        {
            return typeof(NotificationModel<>).MakeGenericType(parameters.ModelType);
        }


        protected override IDictionary<string, object> CreateModelTemplateState(ModelTemplateParameters parameters)
        {
            var result = base.CreateModelTemplateState(parameters);
            //Add the Affected registry to the model state.
            result.Add(Constants.AffectedPropertyRegistry, _affectedProperties.GetOrNew(parameters.ModelType).ToDictionary(kp => kp.Key, kp => kp.Value.ToArray()));
            return result;
        }

        public void Affects(Type modelType, string propertyName, IEnumerable<string> isAffectedByAny)
        {
            var propertyRegistry = _affectedProperties.GetOrCreateNew(modelType);
            foreach (var trigger in isAffectedByAny)
            {
                var affectedProperties = propertyRegistry.GetOrCreateNew(trigger);
                affectedProperties.Add(propertyName);
            }
        }
    }
}
